package org.inter.fsb.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.inter.fsb.utils.ProxyResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class BaseController {

    static final Logger logger = LoggerFactory.getLogger(BaseController.class);
    public static Gson gsonBuilder = (new GsonBuilder()).setDateFormat("yyyy-MM-dd HH:mm:ss").disableHtmlEscaping().create();

    @ExceptionHandler({Exception.class})
    public @ResponseBody ProxyResponse exception(Exception e) {
        logger.error("ExceptionHandler" ,e);
        ProxyResponse<Object> commResponse = new ProxyResponse<>();
        commResponse.setCode(ProxyResponse.STATUS_ERROR);
        String message = e.getMessage();
        commResponse.setMessage(message != null && !message.trim().equals("") ? e.getMessage() : "系统出现错误，请稍后再试");
        return commResponse;
    }

    /**
     * 强制转换为json
     * @param result
     * @param <T>
     * @return
     */
    public <T> ProxyResponse toJson(T result){
        ProxyResponse<T> commResponse = new ProxyResponse<>();
        commResponse.setCode(ProxyResponse.STATUS_SUCCESS);
        commResponse.setMessage("操作成功");
        commResponse.setData(result);
//        return gsonBuilder.toJson(commResponse, ProxyResponse.class);
        return commResponse;

    }
}
